package service

import (
    "context"
    "gitee.com/WisdomClassroom/DisciplineStruct/glb"
    "gitee.com/WisdomClassroom/core"
    "gitee.com/WisdomClassroom/core/models"
    "gitee.com/WisdomClassroom/core/protobufs/v1/pb"
    "github.com/jinzhu/gorm"
    "time"
)

func (s *Service) CreateDiscipline(_ context.Context, in *pb.CreateDisciplineRequest) (*pb.CreateDisciplineResponse, error) {
    token := core.NewToken()
    err := token.UnpackToken(in.AuthToken, &core.FlagTokenCert)
    if err != nil {
        return &pb.CreateDisciplineResponse{Status: &pb.ResponseStatus{
            Code: pb.ResponseStatusCode_NotAuth, Error: err.Error(),
        },}, nil
    }

    if token.Type == core.UserRoleTypeCodeRoot {
        userOfReq := models.UserModel{
            Model: models.Model{
                UUID: token.UUID,
            },
            Type: core.UserRoleTypeCodeRoot,
        }
        err = glb.DB.Scopes(notDeleted).Where(&userOfReq).First(&userOfReq).Error
        if err == gorm.ErrRecordNotFound {
            return &pb.CreateDisciplineResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
                Message: "用户没有权限",
            },}, nil
        } else if err != nil {
            glb.Logger.Error(err.Error())
            return createDisciplineRespSvrErr, nil
        }
    } else {
        // 检查是否为学院管理员
        collegeMngrBindOfReq := models.CollegeManagerBindModel{
            CollegeUUID: in.CollegeUUID,
            ManagerUUID: token.UUID,
        }
        err = glb.DB.Scopes(notDeleted).Where(&collegeMngrBindOfReq).First(&collegeMngrBindOfReq).Error
        if err == gorm.ErrRecordNotFound {
            return &pb.CreateDisciplineResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
                Message: "用户没有权限或编号不存在",
            },}, nil
        } else if err != nil {
            glb.Logger.Error(err.Error())
            return createDisciplineRespSvrErr, nil
        }
    }

    if len(in.Name) == 0 {
        return &pb.CreateDisciplineResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "专业名称未填写",
        },}, nil
    }
    if len(in.CollegeUUID) != 36 {
        return &pb.CreateDisciplineResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "学院编号不正确",
        },}, nil
    }
    if len(in.ManagerUUID) != 36 {
        return &pb.CreateDisciplineResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "管理员编号不正确",
        },}, nil
    }

    college := models.CollegeModel{
        Model: models.Model{
            UUID: in.CollegeUUID,
        },
    }
    err = glb.DB.Scopes(notDeleted).Where(&college).First(&college).Error
    if err == gorm.ErrRecordNotFound {
        return &pb.CreateDisciplineResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "学院编号不存在",
        },}, nil
    } else if err != nil {
        glb.Logger.Error(err.Error())
        return createDisciplineRespSvrErr, nil
    }

    userOfMngrOfArg := models.UserModel{
        Model: models.Model{
            UUID: in.ManagerUUID,
        },
    }
    err = glb.DB.Scopes(notDeleted).Where(&userOfMngrOfArg).First(&userOfMngrOfArg).Error
    if err == gorm.ErrRecordNotFound {
        return &pb.CreateDisciplineResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "管理员编号不存在",
        },}, nil
    } else if err != nil {
        glb.Logger.Error(err.Error())
        return createDisciplineRespSvrErr, nil
    }

    discipline := models.DisciplineModel{
        Model: models.Model{
            UUID:         core.GenUUID(),
            CreationTime: time.Now().Unix(),
        },
        Name:        in.Name,
        Description: in.Description,
    }
    err = glb.DB.Transaction(func(tx *gorm.DB) error {
        if err := tx.Create(&discipline).Error; err != nil {
            return err
        }
        err := tx.Create(&models.CollegeDisciplineBindModel{
            Model: models.Model{
                UUID:         core.GenUUID(),
                CreationTime: time.Now().Unix(),
            },
            CollegeUUID:    in.CollegeUUID,
            DisciplineUUID: discipline.UUID,
        }).Error
        if err != nil {
            return err
        }
        err = tx.Create(&models.DisciplineManagerBindModel{
            Model: models.Model{
                UUID:         core.GenUUID(),
                CreationTime: time.Now().Unix(),
            },
            DisciplineUUID: discipline.UUID,
            ManagerUUID:    in.ManagerUUID,
        }).Error
        if err != nil {
            return err
        }
        return nil
    })
    if err != nil {
        glb.Logger.Error(err.Error())
        return createDisciplineRespSvrErr, nil
    }

    return &pb.CreateDisciplineResponse{
        Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_Suc},
        UUID:   discipline.UUID,
    }, nil
}
